package com.core.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;

import com.core.cache.Cache;
import com.dsp.bean.Company;
import com.dsp.bean.Menu;
import com.dsp.services.MenuService;

/**
 * 
 * @author dsp
 * 
 */
public class JavaScript extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7846164939183464794L;

	Logger logger = Logger.getLogger(DspUtil.Log4J);

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置接收信息的字符集
		try {
			StringBuffer script = new StringBuffer(200);
			request.setCharacterEncoding("UTF-8");
			String type = request.getParameter("type");
			
			if ("province".equalsIgnoreCase(type)) {
				Map<String, String> map = Cache.getProvince();
				script.append(" var " + type + " = new Array();\n");
				put(script, type, map);
			} else if ("item".equalsIgnoreCase(type)) {
				script.append(" var " + type + " = new Array();\n");
				this.showItemCode(type, script);
			} else if ("selectTags".equalsIgnoreCase(type)) {
				script.append(" var " + type + " = new Array();\n");
				this.showSelect(type, script);
			} else if ("Com".equalsIgnoreCase(type)) {
				this.showCompany(type, script);
			} else if ("menu".equals(type)){
				this.showMenu(type,script);
			}
			response.setContentType("text/plain;charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out = response.getWriter();
			out.print(script.toString());
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	private void put(StringBuffer script, String type, Map<String, String> map) {
		for (Iterator<Map.Entry<String, String>> iter = map.entrySet().iterator(); iter.hasNext();) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
			script.append(type).append("['").append(entry.getKey()).append("'] = \"" + DspUtil.gbEncoding(entry.getValue()) + "\";\n");
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) {
		// 设置接收信息的字符集
		try {
			doPost(request, response);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 显示名称
	 * 
	 * @param name
	 */
	private void showItemCode(String name, StringBuffer script) {
		Map<String, String> map = Cache.getItemMap();
		put(script, name, map);
	}

	/**
	 * 下拉框
	 * 
	 * @param name
	 * @param script
	 */
	private void showSelect(String name, StringBuffer script) {
		Map<String, List<Map<String, String>>> map = Cache.getSelect();
		for (Iterator<Map.Entry<String, List<Map<String, String>>>> iter = map.entrySet().iterator(); iter.hasNext();) {
			Map.Entry<String, List<Map<String, String>>> entry = (Map.Entry<String, List<Map<String, String>>>) iter.next();
			String key = entry.getKey();
			List<Map<String, String>> tmp = entry.getValue();
			for (Map<String, String> m : tmp) {
				script.append(name).append("[\"").append(key).append("_").append(m.get("value")).append("\"] = \"")
						.append(DspUtil.gbEncoding(m.get("name"))).append("\";\n");
			}
		}
	}

	/**
	 * 公司信息
	 * 
	 * @param name
	 * @param script
	 */
	private void showCompany(String type , StringBuffer script) {
		Map<String, Company> map = Cache.getCompany();
		script.append(" var "+ type + " = [\n");
		for (Iterator<Map.Entry<String, Company>> iter = map.entrySet().iterator(); iter.hasNext();) {
			Map.Entry<String, Company> entry = (Map.Entry<String, Company>) iter.next();
			script.append("{id:\"" + entry.getKey() + "\" , value:\""+ DspUtil.gbEncoding(entry.getValue().getCname()) +"\"},\n");
		}
		script.append("{id:'',value:''}\n];");
	}
	/**
	 * {"menu":[
						{"menuid":"2","icon":"icon-sys","menuname":"公司",
							"menus":[
									{"menuid":"8","menuname":"公司资料","icon":"icon-add","url":"companys"}
								]
						},{"menuid":"4","icon":"icon-sys","menuname":"员工管理",
							"menus":[{"menuid":"21","menuname":"员工列表","icon":"icon-nav","url":"employees"}
								]
						},{"menuid":"56","icon":"icon-sys","menuname":"部门管理",
							"menus":[{"menuid":"31","menuname":"添加部门","icon":"icon-nav","url":"demo1.html"},
									{"menuid":"32","menuname":"部门列表","icon":"icon-nav","url":"demo2.html"}
								]
						},{"menuid":"28","icon":"icon-sys","menuname":"财务管理",
							"menus":[{"menuid":"41","menuname":"收支分类","icon":"icon-nav","url":"demo.html"},
									{"menuid":"42","menuname":"报表统计","icon":"icon-nav","url":"demo1.html"},
									{"menuid":"43","menuname":"添加支出","icon":"icon-nav","url":"demo2.html"}
								]
						},{"menuid":"39","icon":"icon-sys","menuname":"商城管理",
							"menus":[{"menuid":"51","menuname":"商品分类","icon":"icon-nav","url":"demo.html"},
									{"menuid":"52","menuname":"商品列表","icon":"icon-nav","url":"demo1.html"},
									{"menuid":"53","menuname":"商品订单","icon":"icon-nav","url":"demo2.html"}
								]
						}
				]};
	 * @param type
	 * @param script
	 */
	private void showMenu(String type ,StringBuffer script){
		StringBuffer tmp = new StringBuffer(200);
		script.append(" var _menus = {\"menus\":[ \n");
		MenuService ms = (MenuService)DspUtil.getBean("menuService");
		DetachedCriteria dc = DetachedCriteria.forClass(Menu.class);
		List<Menu> list = ms.likeBy(dc);
		for(Menu menu: list) {
			if("0".equals(menu.getParent())) {
				tmp.append(",{ ");
				tmp.append("\"id\":\""+menu.getId()+"\" , \"icon\":\"icon-sys\",\"tag\":\""+ menu.getTag()+"\"");
				boolean isHeader = true;
				for(Menu subMenu : list){
					if(menu.getId().equals(subMenu.getParent())){
						if(isHeader){
							tmp.append(" , \"menus\":[");
							isHeader = false;
						}
						tmp.append("\"id\":\""+subMenu.getId()+"\" , \"icon\":\"icon-sys\",\"tag\":\""+ subMenu.getTag()+"\",\"url\":\""+ subMenu.getEvent()+"\"");
					}
				}
				if (!isHeader){
					tmp.append("]");
				}
				tmp.append("}");
			}
		}
		if(tmp.length() > 1){
			script.append(tmp.substring(1));
		}
		script.append("]};");
	}
}
